// socket功能
import Stomp from "stompjs";
import store from "../store";
import config from "../config";
import { nextTick } from "vue";
import { ElNotification } from "element-plus";
import router from "../router";
import { setHasReadByIds } from "../api/message/message.api";
import bus from "./bus";
import {
  showBrowserNotification,
  canUseBrowserNotification,
} from "./notification";

// import.meta.globEager("./sockjs.js");

let connectionTimer = null;
let countdown = 10;
let socket = null;
let stompClient = null;
let isDisconnect = false;

export function initWebSocket(code) {
  isDisconnect = false;
  socket = new window.SockJS(config.webSocketUrl + "/ws"); // 连接SockJS的endpoint名称为"ws"
  console.log("webSocket 连接地址：" + config.webSocketUrl + "/ws");
  // 获取 STOMP 子协议的客户端对象
  stompClient = Stomp.over(socket);
  const headers = {
    Authorization: store.state.user.token,
  };
  // 拦截输出
  stompClient.debug = function (str) {
    console.log(str);
  };
  // 向服务器发起websocket连接
  stompClient.connect(
    headers,
    () => {
      console.log("socket 连接成功！", stompClient.connected);
      // 处理当连接开始建立时，调用了 disconnectSocket ，但是连接没有被中断的问题
      if (isDisconnect) {
        return disconnectSocket();
      }
      // 订阅服务端提供的某个 topic（可以在后面接着写多个订阅）

      /**
       * 订阅消息模块
       */
      stompClient.subscribe("/user/" + code + "/queue/info", (response) => {
        // console.log("订阅服务端返回 ===>", response);
        if (response.body) {
          const result = JSON.parse(response.body);
          console.log("result ===>", result);
          notifyMsg(result);
          if (!store.state.pageVisible && canUseBrowserNotification()) {
            showBrowserNotification({
              title: "日报管理系统",
              content: "收到一条消息，请及时查看",
            });
          }
          store.dispatch("message/getUnReadCount");
          bus.emit("messageTableHandleSearch");
        }
      });

      /**
       * 其他订阅...
       */
    },
    (err) => {
      // 连接发生错误时的处理函数
      console.log("socket 连接失败 error: ", err);
    }
  );

  socket.onclose = function () {
    console.log("socket 已断开连接");
    if (!isDisconnect) {
      startCountdown(initWebSocket);
    }
  };
}

function startCountdown(fn) {
  clearInterval(connectionTimer);
  countdown = 10;
  connectionTimer = setInterval(() => {
    console.log(`${countdown}秒钟后自动重连...`);
    countdown--;
    if (countdown <= 0) {
      clearInterval(connectionTimer);
      connectionTimer = null;
      fn();
    }
  }, 1000);
}

export function disconnectSocket() {
  isDisconnect = true;
  if (stompClient) {
    try {
      stompClient.disconnect();
      socket.close();
      stompClient = null;
      socket = null;
      console.log("调用了连接关闭");
    } catch (err) {
      console.log("disconnectSocket error: ", err);
    }
  }
}

// window.addEventListener("offline", function (e) {
//   console.log("监听到 offline 事件 ===>");
//   if (stompClient) {
//     stompClient.disconnect();
//     socket.close();
//   }
//   console.log("socket 连接已断开");
//   console.log(stompClient.connected);
// });

// window.addEventListener("online", function (e) {
//   console.log("监听到 online 事件 ===>");
//   connectionTimer = setInterval(initWebSocket, 3000);
// });

/**
 type:
  0: "其他消息",
  1: "系统消息",
  2: "日报消息",
  3: "周报消息",
  4: "个人消息",
 */
function notifyMsg(msgData, fn) {
  switch (msgData.type) {
    case "4":
      // 刷新用户信息
      store.dispatch("user/getUserInfo");
      break;
    default:
  }
  // 消息提示框
  nextTick(() => {
    const notice = ElNotification({
      title: msgData.typeLabel,
      message: msgData.title,
      duration: 0,
      onClick: () => {
        switch (msgData.type) {
          case "2":
            router.push("/TodayReportManage");
            break;
          default:
        }
        notice.close();
        setHasReadByIds({
          ids: [msgData.id],
        })
          .then((res) => {
            store.dispatch("message/getUnReadCount");
            switch (msgData.type) {
              case "2":
                bus.emit("TodayReportManageHandleSearch");
                break;
              default:
            }
          })
          .catch((err) => {
            console.error("setHasReadByIds error: ", err);
          });
      },
    });
  });
}
